package com.niannian.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.MyDate;
import com.niannian.util.UmengPage;
import com.niannian.adapter.SystemNewsAdaper;
import com.niannian.bean.GreetingNewsBean;
import com.niannian.bean.SystemNewsBean;
import com.niannian.util.LoadDataUtil;
import com.niannian.view.PullToRefreshListView;
import com.niannian.view.PullToRefreshListView.IXListViewListener;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 发送的问候
 * 
 * @author shengl
 * 
 */
public class SystemNewsActivity extends BaseActivity {

	public static final int LIST_FOOTER_HIDE = 3;// 隐藏底部
	// 动态显示列表
	private PullToRefreshListView list_system_news_info;
	private SystemNewsAdaper gAdapter;
	private LoadData loadData;// 加载动态

	TextView tv_no_data;// 没有数据的提示

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_system_news);

		initView();
		setLister();
		initTopView();
		loadData = new LoadData();
		loadData.setContext(this);
		loadData.loadOnlyDb(false, getParameters());
		loadData.refresh(getParameters());

		try {
			Intent msgIntent = new Intent(MessageRecieveManager.UPDATA_NEWSS_TOTAL_COUNT_ACTION);
			String msg_type = "S";
			msgIntent.putExtra("msg_type", msg_type);
			sendBroadcast(msgIntent);

			int senderid = getIntent().getIntExtra("id", 0);
			NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			notiManager.cancel(senderid);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("系统消息");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);

		iv_top_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myfinish();
			}
		});

	}

	private void initView() {
		list_system_news_info = (PullToRefreshListView) findViewById(R.id.list_system_news_info);
		list_system_news_info.setXListViewListener(xListViewListener);
		list_system_news_info.setPullLoadEnable(false);
		// list_system_news_info.forceShowHeaderRefresh();
		gAdapter = new SystemNewsAdaper(this);
		list_system_news_info.setAdapter(gAdapter);
		gAdapter.setAdapter(gAdapter);
		tv_no_data = (TextView) findViewById(R.id.tv_no_data);
		tv_no_data.setVisibility(View.GONE);

	}

	private void updateContent(List<SystemNewsBean> beans) {
		if (gAdapter == null) {
			gAdapter = new SystemNewsAdaper(this);
			list_system_news_info.setAdapter(gAdapter);
		}
		gAdapter.getDatasList().addAll(beans);
		gAdapter.notifyDataSetChanged();

		if (gAdapter.getCount() > 0) {
			tv_no_data.setVisibility(View.GONE);
		} else {
			tv_no_data.setVisibility(View.VISIBLE);
		}
	}

	private void setLister() {

	}

	private Map<String, Object> getParameters() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lasttime", 0);
		return map;
	}

	class LoadData extends LoadDataUtil {

		@Override
		protected String runServerTask(Map<String, Object> parameters) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			return nnSyncApi.getSystemNewssInfo(lasttime);
		}

		protected void serverTaskFinally(Map<String, Object> params) {
			onLoad();
		}

		@Override
		protected boolean handleServerSuccess(JSONObject json, Map<String, Object> parameters) {
			onLoad();
			try {
				if (json.getInt("code") == ErrorCode.OK) {
					int lasttime = 0;
					if (!Common.empty(parameters.get("lasttime"))) {
						lasttime = (Integer) parameters.get("lasttime");
					}
					databaseapi.updateSystemNews(userInfoManager.id, json.getJSONArray("data"), lasttime);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected boolean loadMoreDB(Map<String, Object> parameters, boolean refresh) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			List<SystemNewsBean> fdata = databaseapi.loadSystemNews(userInfoManager.id, lasttime);
			list_system_news_info.listNotData(true);
			if (fdata != null) {
				// if (fdata == null || fdata.size() == 0) {
				//
				// list_greeting_send_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// }
				// if (fdata.size() != 10) {
				// list_greeting_send_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// } else {
				// list_greeting_send_info.listNotData(true);
				// }
				if (lasttime == 0) {
					gAdapter.getDatasList().clear();
				}
				updateContent(fdata);
			} else {
				if (refresh) {
					if (gAdapter.getCount() > 0) {
						tv_no_data.setVisibility(View.GONE);
					} else {
						tv_no_data.setVisibility(View.VISIBLE);
					}
				}
			}
			return false;
		}
	}

	private IXListViewListener xListViewListener = new IXListViewListener() {
		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					loadData.refresh(getParameters());
				}
			}, 500);
		}

		@Override
		public void onLoadMore() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					GreetingNewsBean last = null;
					try {
						last = (GreetingNewsBean) gAdapter.getItem((gAdapter.getCount() - 1));
					} catch (Exception e) {
						last = null;
					}
					if (last != null) {
						map.put("lasttime", last.getSent_time());
					} else {
						map.put("lasttime", 0);
					}
					loadData.load(map);
				}
			}, 150);
		}
	};

	private void onLoad() {// 显示拉出来时候的一些信息
		list_system_news_info.stopRefresh();
		list_system_news_info.stopLoadMore();
		list_system_news_info.setRefreshTime(MyDate.getDate());
	}

	@Override
	public void onBackPressed() {

		myfinish();
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPage.system_msg_face);
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPage.system_msg_face);
		MobclickAgent.onPause(this);
	}

}
